package com.cykj.service.impl;

import com.cykj.mapper.MenuMapper;
import com.cykj.pojo.CyMenu;
import com.cykj.service.MenuService;
import com.cykj.util.ResponseDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    ArrayList<CyMenu> menuData = new ArrayList<CyMenu>();
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ResponseDto getAllMenu(int roleId) {
        ArrayList<CyMenu> menuData = new ArrayList<CyMenu>();

        List<CyMenu> allMenu = menuMapper.getPermissionMenu(roleId);
        for (CyMenu menu : allMenu) {
            //如果等于0说明是一级菜单
            if (menu.getMenuParentId() == 0){
                //把一级菜单传过去，把所有的菜单传过去，让一级菜单去找对应的子级菜单
                menuData.add(getChildrenMenu(menu,allMenu));
            }
        }
        return new ResponseDto(1,"成功",menuData);
    }

    public CyMenu getChildrenMenu(CyMenu nowCyMenu,List<CyMenu> allMenu){
        //当前的父级菜单nowCyMenu 和 所有的菜单
        for (CyMenu menu : allMenu) {
            //如果当前的父级菜单的id等于子级菜单的父id，说明是它的子级，然后不断判断和添加
            if (nowCyMenu.getMenuId() == menu.getMenuParentId()){
                nowCyMenu.getChildren(  ).add(getChildrenMenu(menu,allMenu));
            }
        }
        //最后返回一个一级菜单以及它全部的子孙后代
        return nowCyMenu;
    }
}
